package jrain.utils.prop;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.URL;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

import jrain.utils.consts.BaseConst;
import jrain.utils.exception.ServiceException;
import jrain.utils.io.IoUtils;
import jrain.utils.lang.StringUtils;

/**
 * <pre>
 * 作者：489088214@qq.com 
 * 描述： 配置工具类
 * </pre>
 */
public class PropUtils {

	/**
	 * 获取配置
	 * @param propPath 配置路径
	 * @return 配置Map
	 */
	public static Map<String, Object> getClasspathConf(String propPath) {
		Map<String, Object> cfg = new HashMap<>();
		ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
		try {
			Enumeration<URL> urls = classLoader.getResources(propPath);
			if (urls != null && urls.hasMoreElements()) {
				if (urls.hasMoreElements()) {
					URL url = urls.nextElement();
					InputStream in = null;
					Reader ir = null;
					BufferedReader br = null;
					try {
						in = url.openStream();
						ir = new InputStreamReader(in, BaseConst.UTF8);
						br = new BufferedReader(ir);
						String str = null;
						while ((str = br.readLine()) != null) {
							str = StringUtils.trimNull(str);
							if (!str.startsWith("#")) {
								int index = str.indexOf("=");
								if (index > -1) {
									String key = StringUtils.trimNull(str.substring(0, index));
									String value = StringUtils.trimNull(str.substring(index + 1));
									if (!StringUtils.isEmpty(key)) {
										cfg.put(key, value);
									}
								}
							}
						}
					} finally {
						IoUtils.closeReader(br);
						IoUtils.closeReader(ir);
						IoUtils.closeIn(in);
					}
				}
			}
			return cfg;
		} catch (Exception e) {
			throw new ServiceException(e.getMessage(), e);
		}
	}

	/**
	 * 获取配置文件数据
	 * @param propPath 配置路径
	 * @return 配置Map
	 */
	public static Map<String, Object> getClasspathData(String propPath) {
		Map<String, Object> cfg = new HashMap<>();
		ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
		try {
			Enumeration<URL> urls = classLoader.getResources(propPath);
			if (urls != null && urls.hasMoreElements()) {
				if (urls.hasMoreElements()) {
					URL url = urls.nextElement();
					Properties properties = new Properties();
					InputStream in = null;
					try {
						in = url.openStream();
						properties.load(in);
					} finally {
						if (in != null) {
							in.close();
						}
					}
					Enumeration<Object> keys = properties.keys();
					while (keys.hasMoreElements()) {
						String key = (String) keys.nextElement();
						cfg.put(key, (String) properties.get(key));
					}
				}
			}
			return cfg;
		} catch (Exception e) {
			throw new ServiceException(e.getMessage(), e);
		}
	}

}
